﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace dreametryVersion2
{
    public partial class frmUpdateEmployee : Form
    {
        public frmUpdateEmployee()
        {
            InitializeComponent();
        }

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;
        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        private void frmUpdateEmployee_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void getEmployeeInfo()
        {
            string commandText = "SELECT * FROM employee WHERE emp_id='" + global.employeeID + "'";

            using (SqlConnection connection = new SqlConnection(global.conString))
            {
                SqlCommand command = new SqlCommand(commandText, connection);
                command.Connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    txtFullname.Text = reader["fullname"].ToString();
                    txtUsername.Text = reader["username"].ToString();
                    picEmployee.Image = Image.FromStream(global.getEmployeePicture((byte[])reader["picture"]));
                    txtColor.Text = reader["color_scheme"].ToString();
                }
            }
        }

        private void picEmployee_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "jpg|*.jpg";
            DialogResult result = openFileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                picEmployee.Image = Image.FromFile(openFileDialog.FileName);
            }
        }

        private void btnSaveInfo_Click(object sender, EventArgs e)
        {
            if(btnSaveInfo.Text == "save")
            {
                lblMessageInfo.Text = "Something went wrong";

                if(txtFullname.Text == "" || txtUsername.Text == "" || txtColor.Text.Length != 7)
                {
                    lblMessageInfo.Visible = true;
                }
                else
                {
                    lblEnterPasswordInfo.Visible = true;
                    pnlEnterPassword.Visible = true;
                    lblMessageInfo.Visible = false;
                    txtConfirmInfo.Visible = true;
                    txtConfirmInfo.Focus();
                    txtFullname.Enabled = false;
                    txtUsername.Enabled = false;
                    picEmployee.Enabled = false;
                    txtColor.Enabled = false;
                    btnSaveInfo.Text = "continue";
                }
            }
            else
            {
                string commandText1 = "SELECT COUNT(*) FROM employee WHERE emp_id = '" + global.employeeID + "' and password='" + global.CalculateMD5Hash(txtConfirmInfo.Text) + "'";
                int count;

                using (SqlConnection connection = new SqlConnection(global.conString))
                {
                    SqlCommand command = new SqlCommand(commandText1, connection);
                    command.Connection.Open();
                    count = Int32.Parse(command.ExecuteScalar().ToString());
                }
                    if(count == 1)
                    {
                        string commandText2 = "UPDATE employee SET fullname = '" + txtFullname.Text + "', username = '" + txtUsername.Text + "', picture = @picture , color_scheme='" + txtColor.Text + "' WHERE emp_id = '" + global.employeeID + "'";

                        using (SqlConnection connection = new SqlConnection(global.conString))
                        {
                            SqlCommand command = new SqlCommand(commandText2, connection);
                            command.CommandType = CommandType.Text;
                            MemoryStream stream = new MemoryStream();
                            picEmployee.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                            byte[] picture = stream.ToArray();
                            command.Parameters.AddWithValue("@picture", picture);
                            command.Connection.Open();
                            command.ExecuteNonQuery();
                        }
                        this.Hide();
                        message.Ok("Update account","The application will exit, Please login again");
                        Application.Exit();
                    }
                    else
                    {
                        txtConfirmInfo.Text = "";
                        lblMessageInfo.Text = "wrong password";
                        lblMessageInfo.Visible = true;
                    } 
                }
            }

        private void frmUpdateEmployee_Load(object sender, EventArgs e)
        {
            this.BackColor = ColorTranslator.FromHtml(global.themeColor);
            btnSaveInfo.BackColor = ColorTranslator.FromHtml(global.themeColor);
            btnSavePassword.BackColor = ColorTranslator.FromHtml(global.themeColor);
            pnlFullname.BackColor = ColorTranslator.FromHtml(global.themeColor);
            pnlUsername.BackColor = ColorTranslator.FromHtml(global.themeColor);
            pnlColorTheme.BackColor = ColorTranslator.FromHtml(global.themeColor);
            pnlEnterPassword.BackColor = ColorTranslator.FromHtml(global.themeColor);
            pnlCurrentPassword.BackColor = ColorTranslator.FromHtml(global.themeColor);
            pnlNewPassword.BackColor = ColorTranslator.FromHtml(global.themeColor);
            pnlConfirmPassword.BackColor = ColorTranslator.FromHtml(global.themeColor);
            getEmployeeInfo();
        }

        private void txtFullname_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                btnSaveInfo.PerformClick();
            }
        }

        private void txtUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSaveInfo.PerformClick();
            }
        }

        private void txtConfirmInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSaveInfo.PerformClick();
            }
        }

        private void btnSavePassword_Click(object sender, EventArgs e)
        {
            if(txtCurrentPassword.Text == "" || txtNewPassword.Text == "" || txtConfirmPassword.Text == "")
            {
                lblMessagePassword.Text = "please fill all fields";
            }
            else if(txtNewPassword.Text != txtConfirmPassword.Text)
            {
                lblMessagePassword.Text = "new passwords don't match";
            }
            else
            {
                string commandText1 = "SELECT COUNT(*) FROM employee WHERE emp_id = '" + global.employeeID + "' and password='" + global.CalculateMD5Hash(txtCurrentPassword.Text) + "'";
                int count;

                using (SqlConnection connection = new SqlConnection(global.conString))
                {
                    SqlCommand command = new SqlCommand(commandText1, connection);
                    command.Connection.Open();
                    count = Int32.Parse(command.ExecuteScalar().ToString());
                }

                if (count == 1)
                {
                    string commandText2 = "UPDATE employee SET password = '" + global.CalculateMD5Hash(txtNewPassword.Text) + "' WHERE emp_id = '" + global.employeeID + "'";

                    using (SqlConnection connection = new SqlConnection(global.conString))
                    {
                        SqlCommand command = new SqlCommand(commandText2, connection);
                        command.CommandType = CommandType.Text;
                        command.Connection.Open();
                        command.ExecuteNonQuery();
                    }
                    Application.Exit();
                }
                else
                {
                    lblMessagePassword.Text = "wrong password";
                }
            }
        }

        private void txtCurrentPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                btnSavePassword.PerformClick();
            }
        }

        private void txtCurrentPassword_TextChanged(object sender, EventArgs e)
        {
            lblMessagePassword.Text = "";
        }

        private void txtConfirmInfo_TextChanged(object sender, EventArgs e)
        {
            if (lblMessageInfo.Visible == true)
            {
                lblMessageInfo.Visible = false;
            }
        }

        private void txtUsername_TextChanged(object sender, EventArgs e)
        {
            if (lblMessageInfo.Visible == true)
            {
                lblMessageInfo.Visible = false;
            }
        }

        private void txtFullname_TextChanged(object sender, EventArgs e)
        {
            if (lblMessageInfo.Visible == true)
            {
                lblMessageInfo.Visible = false;
            }
        }

        public void processRGBColor()
        {
            Color color = Color.White;
            try
            {
                color = System.Drawing.ColorTranslator.FromHtml(txtColor.Text);
                lblMessageInfo.Visible = false;
            }
            catch
            {
                lblMessageInfo.Text = "Color not found";
                lblMessageInfo.Visible = true;
            }

            pnlColorTest.BackColor = color;
        }

        private void txtR_TextChanged(object sender, EventArgs e)
        {
            processRGBColor();
        }

        private void txtColor_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSaveInfo.PerformClick();
            }
        }
    }
}
